/**
 * Copyright (C) 2011 GreenSoft S.A.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.com.greensoft.jeecommons.web.jsf.converters;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import ar.com.greensoft.neosystem.dao.DaoException;
import ar.com.greensoft.neosystem.dao.GenericDao;


/**
 * @author Jorge E. Villaverde
 * @version 1.0.0
 * @since 09/07/2011	
 */
public abstract class GenericConverter<T, PK extends Serializable> implements Converter, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1105260213657474675L;
	private static final Logger logger = Logger.getLogger(GenericConverter.class.getName());
	private GenericDao<T, PK> dao;
	
	public GenericConverter(GenericDao<T, PK> dao) {
		super();
		this.dao = dao;
	}

	public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (context == null || component == null) {
            throw new NullPointerException();
        }

        // If the specified value is null or zero-length, return null
        if (value == null || "null".equals(value)) {
            return (null);
        }
        value = value.trim();
        if (value.length() < 1) {
            return (null);
        }
		
        PK id;
		try {
			if(logger.isLoggable(Level.FINE))
	    		logger.fine("Converting Entity with id: " + value);

			id = parserId(value);
			
			T entity = dao.findById(id);
			
			if(logger.isLoggable(Level.FINE))
	    		logger.fine("Entity converted: " + entity);
			
			return entity;
		} catch (NumberFormatException e) {
			logger.severe(e.getMessage());
		} catch (DaoException e) {
			logger.severe(e.getMessage());
		}
		return null;
	}
	
	protected abstract PK parserId(String value);
	protected abstract PK getId(T entity);
	
	@SuppressWarnings("unchecked")
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		try {
			return String.valueOf(getId((T)value));
		} catch (ClassCastException e) {
		}
		return "";
	}
}